package org.shj.zookeeper.lock;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.ZooKeeper;


public class LockService {
	
	private static final int THREAD_NUM = 10; 
	public static   CountDownLatch threadSemaphore = new CountDownLatch(THREAD_NUM);
	
	AbstractZooKeeper az = new AbstractZooKeeper();
	
	public void doService(DoTemplate doTemplate){
		try {
			ZooKeeper zk = az.connect(Constants.CONNECTION_STRING, Constants.SESSION_TIMEOUT);
			DistributedLock dc = new DistributedLock(zk);
			LockWatcher lw = new LockWatcher(dc,doTemplate);
			dc.setWatcher(lw);
			//GROUP_PATH不存在的话，由一个线程创建即可；
			dc.createPath(Constants.GROUP_PATH, "该节点由线程"+Thread.currentThread().getName() + "创建");
			boolean rs = dc.getLock();
			if (rs) {
				lw.dosomething();
				dc.unlock();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
